//路由鉴权
import router from "./router"
import nprogress from "nprogress"
import "nprogress/nprogress.css"
nprogress.configure({ showSpinner: false })
//任意路由切换都会触发的钩子
//全局前置守卫

//获取用户信息-仓库数据
import pinia from "./store"
import useUserStore from "./store/modules/user"

const UserStore = useUserStore(pinia)
//任意路由切换实现进度条业务 --nprogress
//路由鉴权（路由组件访问权限设置）
//

router.beforeEach(async (to: any, from: any, next: any) => {
  //to 访问那个路由 from 从哪个路由而来 next 路由的放行行数
  //访问某一个路由之前守卫
  nprogress.start()
  //获取token
  const token = UserStore.token
  if (token) {
    if (to.path == "/login") {
      next({ path: "/home" })
    } else {
      //登录成功访问其余路由
      try {
        await UserStore.userInfo()
        next()
      } catch (error) {
        //token过期 本地缓存清除
        await UserStore.userLogout()
        next({ path: "/login", query: { redirect: to.path } })
      }
    }
  } else {
    if (to.path == "/login") {
      next()
    } else {
      next({ path: "/login", query: { redirect: to.path } })
    }
  }
})

//全局后置守卫

router.afterEach((to: any) => {
  document.title = "贵州甑选-" + to.meta.title
  nprogress.done()
})
